package com.smbms.controller;

import com.alibaba.fastjson.JSON;
import com.smbms.pojo.Role;
import com.smbms.pojo.User;
import com.smbms.service.UserService;
import com.smbms.util.PageBean;
import com.sun.javafx.image.BytePixelSetter;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.naming.NoPermissionException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/user")
public class UserController {
    Logger logger = Logger.getLogger(UserController.class);
    @Resource
    private UserService userService;

    @RequestMapping("/delete/{userId}")
    @ResponseBody  // 不加responseBody 走的是请求转发  加 返回数据到当前页面
    public String deleteUser(@PathVariable Integer userId){
        Map<String,Object> map = new HashMap<>();
        int row = userService.deleteUser(userId);
        if (row >0){
            map.put("delResult","true");
        }else if(row == 0){
            map.put("delResult","notexist");
        }else{
            map.put("delResult","false");
        }

        return JSON.toJSONString(map);
    }

    @RequestMapping("/modifyUser")
    public String modifyUser(HttpSession session,@ModelAttribute User user){
        User loginUser = (User) session.getAttribute("loginUser");
        user.setModifyBy(loginUser.getId());
        user.setModifyDate(new Date());
        boolean result = userService.modifyUser(user);
        if (result){
            return "redirect: /user/userlist";
        }else{
            return "usermodify";
        }
    }

    @RequestMapping("/toModify/{userId}")
    public String toModify(HttpServletRequest request,@PathVariable Integer userId){
        User user = userService.getUser(userId);
        request.setAttribute("user",user);
        return "usermodify";
    }

    @RequestMapping("/view/{userId}")
    public String userView(HttpServletRequest request,@PathVariable Integer userId){
        User user = userService.getUser(userId);
        if (user != null){
            request.setAttribute("user",user);
            return "userview";
        }else{
            return "redirect: /user/userlist";
        }

    }

    @RequestMapping("/useraddsave")
    public String userAddSave(HttpSession session, HttpServletRequest request,
                              @RequestParam(value = "a_idPicPath",required = false) MultipartFile multipartFile, User user){
        String idPicPathError = "";
        String newFileName = "";
        String fileUploadPath = "";
        // 1.判断是否上传了文件
        if (multipartFile != null){
            // 1.进行文件上传准备工作
            // 1.1 准备文件上传的路径
            // 获取绝对路径
            fileUploadPath = session.getServletContext().getRealPath("statics"+File.separator+"uploadFiles");
            logger.info(fileUploadPath);
            // 1.2 获取文件名
            String fileName = multipartFile.getOriginalFilename();
            // 1.3 获取文件大小
            if (multipartFile.getSize() > 5000000){
                idPicPathError = "上传的文件超出限制大小!!!";
                request.setAttribute("idPicPathError",idPicPathError);
                return "useradd";
            }
            // 判断后缀名是否符合
            String suffix = fileName.substring(fileName.indexOf(".")+1);
            String prefix = fileName.substring(0,fileName.indexOf("."));

            // 判断是否符合要的文件格式

            List<String> list = new ArrayList<String>();
            list.add("jpg");
            list.add("jpeg");
            list.add("png");
            if (!list.contains(suffix)){
                request.setAttribute("idPicPathError","文件格式不支持!!请上传jpg jpeg png格式的文件");
                return "useradd";
            }

            // 定义上传的文件名
            newFileName = prefix+(int)(Math.random()*(100000-10000)+10000)+""+System.currentTimeMillis()+"."+suffix;
            File file = new File(fileUploadPath,newFileName);
            if (!file.exists()){
                file.mkdirs();//创建文件夹
            }
            // 开始文件上传
            try {
                multipartFile.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
                request.setAttribute("idPicPathError","系统错误!请重试!");
                return "useradd";

            }
        }
        user.setCreationDate(new Date());
        User loginUser = (User) session.getAttribute("loginUser");
        user.setCreatedBy(loginUser.getId());
        // 添加文件路径 此处修改为相对路径
        user.setIdPicPath(File.separator+"statics"+File.separator+"uploadFiles"+File.separator+newFileName);
        boolean result = userService.userAddSave(user);
        if (result){
            return "redirect: /user/userlist";
        }else{
            return "useradd";
        }


    }

    // @PathVariable:接收路径上的参数
    @RequestMapping("/userCodeIsExists/{userCode}")
    @ResponseBody
    public String userCodeIsExists(@PathVariable String userCode){
        Map<String,Object> map = new HashMap<>();
        // 根据userCode 查询对象
        User user = userService.checkUserCode(userCode);
        if (user != null){
            map.put("userCode","exist");
        }else{
            map.put("userCode","noexist");
        }
        return JSON.toJSONString(map);
    }

    @RequestMapping("/touseradd")
    public String toUserAdd(){
        return "useradd";
    }
    // 如果你是ajax请求请记住如下注解   ajax请求不会再请求转发
    /*produces = "application/json;charset=utf-8":灵活   每次需要配置 */
    @RequestMapping(value = "/getRoleList")
    @ResponseBody
    public String getRoleList(){
        List<Role> roleList = userService.getRoleList();
        // 转成json 字符串
        return JSON.toJSONString(roleList);
    }



    @RequestMapping("/userlist")
    public String userList(String pageIndex,HttpServletRequest request,String queryname,Integer queryUserRole){
        // 起始页
        int index = 1;
        if (pageIndex != null){
            index = Integer.parseInt(pageIndex);
        }
        // 设置每页显示多少条
        int pageSize = 5;
        Map<String,Object> map = new HashMap<>();
        map.put("index",index);
        map.put("pageSize",pageSize);
        map.put("queryname",queryname);
        map.put("queryUserRole",queryUserRole);

        PageBean<User> page = userService.getPage(map);

        // 查询角色列表
        List<Role> roleList = userService.getRoleList();
        request.setAttribute("roleList",roleList);
        request.setAttribute("page",page);

        // 回显
        request.setAttribute("queryUserName",queryname);
        request.setAttribute("queryUserRole",queryUserRole);
        return "userlist";
    }


    @RequestMapping("/logout")
    public String logOut(HttpSession session){

        session.removeAttribute("loginUser");
        return "login";
    }

    @RequestMapping("/login")
    public String login(HttpSession session) throws NoPermissionException{
        // 判断是否有session 有的话放行 没有的话报一个权限异常
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null){
            throw new NoPermissionException("对不起你没有登录,几秒后跳转到登录界面!");
        }
        return "frame";
    }

    @RequestMapping("/dologin")
    public String doLogin(HttpServletRequest request, String userCode, String userPassword){
        if (userCode != null && userPassword != null){
            User user = userService.login(userCode,userPassword);
            if (user == null){
                request.setAttribute("error","用户名或者密码错误!");
                return "login";
            }
            request.getSession().setAttribute("loginUser",user);
            return "redirect:/user/login";//TODO 重定向
        }else{
            request.setAttribute("error","用户名或者密码不能为空");
            return "login";
        }

    }

}
